﻿using System;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Windows.Browser;
using System.Windows.Navigation;
using Infrastructure.Controls;
using MVVMBasic.View.Login;
using MVVMBasicRIALibrary;

namespace MVVMBasic.View
{
    public partial class CustomerListView
    {
        public CustomerListView()
        {
            InitializeComponent();
            this.Title = "Lista klientów";
            this.Loaded += CustomerListView_Loaded;
        }

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        void CustomerListView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if(HtmlPage.Document.QueryString.ContainsKey("actcode"))
            {
                var activationWindow = new ActivationWindow();
                activationWindow.Show();
            }
        }

        private void BtnLoginClick(object sender, System.Windows.RoutedEventArgs e)
        {
            var registrationWindow = new LoginRegistrationWindow();
            registrationWindow.Show();
            registrationWindow.Closed += registrationWindow_Closed;
        }

        void registrationWindow_Closed(object sender, EventArgs e)
        {
            if(WebContext.Current.User.IsAuthenticated)
            {
                btnLogout.IsEnabled = true;
                btnLogin.IsEnabled = false;
            }
        }

        private void BtnLogoutClick(object sender, System.Windows.RoutedEventArgs e)
        {
            WebContext.Current.Authentication.Logout(LogoutOperationCompleted, null);
        }

        private void LogoutOperationCompleted(LogoutOperation logoutOperation)
        {
            if (logoutOperation.IsComplete)
            {
                btnLogout.IsEnabled = false;
                btnLogin.IsEnabled = true;
            }
            else if (logoutOperation.HasError)
            {
                var errWnd = new ErrorWindow { Message = logoutOperation.Error.Message };
                logoutOperation.MarkErrorAsHandled();
                errWnd.Show();
            }
        }
    }
}
